﻿// Copyright (C) 2012 Kim Jensen, TaskJunction.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaskJunctionLib.Mapping.JSON;
using TaskJunctionLib.Model;
using System.Json;
using TaskJunctionLib.Communication;

namespace TaskJunctionLib.Repository
{
    public class ProjectMemberRepository : CachableRepository<ProjectMember, ProjectMemberMapper>, IProjectMemberRepository
    {
        protected override string GetResourceName()
        {
            return "project_members";
        }

        public IList<ProjectMember> LoadListByProjectId(int projectId)
        {
            return GetList(projectId);
        }

        public User LoadUserByUserId(int userId, int projectId)
        {
            var projectMember = GetList(projectId).FirstOrDefault(x => x.UserId == userId);
            return (projectMember == null) ? null : projectMember.User;
        }

        public IList<User> LoadUserListByProjectId(int projectId)
        {
            return GetList(projectId).Select(x => x.User).ToList();
        }

        public void AddMember(Project project, string email)
        {
            var data = new JsonObject { { "project_id", project.Id }, { "email", email } };
            ClearCache();
            Client.Post(GetResourceName(), data.ToString());
        }

        private IList<ProjectMember> GetList(int projectId)
        {
            if (!UseCaching || Cache == null || projectId != CacheProjectId)
            {
                ClearCache();
                var list = _LoadList(GetResourceNameByValues(new Dictionary<string, string> { { "project_id", projectId.ToString() } }));
                CacheProjectId = projectId;
                return list;
            }
            return Cache;
        }

        public override void ClearCache()
        {
            CacheProjectId = 0;
            Cache = null;
        }

        private int CacheProjectId;
    }
}
